package com.hyzh.hj212.test.client;

import com.coffee.netty.CommandHandler;
import com.coffee.netty.connection.CoffeeConnectionFactory;
import com.coffee.netty.connection.Connection;
import com.hyzh.hj212.netty.HjCoder;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author songkui
 * @since 2024/8/5 17:52
 */
public class HjClient {

    private CoffeeConnectionFactory connectionFactory;

    private static HjClient client = new HjClient();

    private HjClient(){
        connectionFactory = new CoffeeConnectionFactory();
        connectionFactory.registerCommandHandler(new CommandHandler() {
            @Override
            public void handleCommand(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
                System.out.println("handleCommand   handleCommand");
            }

            @Override
            public void channelInactive(ChannelHandlerContext channelHandlerContext) throws Exception {

                System.out.println("**************** channelInactive   channelInactive");
            }
        });
        connectionFactory.registerRpcCodec(new HjCoder());
        connectionFactory.registerHeartbeatProcessor(new HeartHandler());
        connectionFactory.setHeartSecond(10L);
        connectionFactory.init();
    }

    public static HjClient getInstance(){
        return client;
    }

    public Connection connection(String ip, int port, int serverId)throws Exception{
        return connectionFactory.connection(ip, port, serverId,3000);
    }

    public static void main(String[] args) {
        try {

            Connection connection =   HjClient.getInstance().connection("127.0.0.1", 28000, 1);
            sendTestData(connection);

            TimeUnit.SECONDS.sleep(60);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private static void sendTestData(Connection future) {
        // 构造符合HJ 212-2017标准的数据包
        String testData = "##0134ST=22;CN=2011;PW=123456;MN=88888880000001;CP=&&DataTime=20181216010101;001-Rtd=23.4,001-Flag=N;002-Rtd=24.5,002-Flag=N&&";

        // 计算数据长度并添加报文头和校验码等
        int length = testData.length();
        String frame = "##" + String.format("%04d", length) + testData;

        // 计算校验码
        int crc = 0;
        for (char c : frame.toCharArray()) {
            crc += (int) c;
        }
        crc = crc & 0xFFFF; // 取低16位

        frame += String.format("%04X", crc) + "\r\n";

        System.out.println("Sending: " + frame);

        // 发送数据
        ByteBuf message = Unpooled.copiedBuffer(frame, StandardCharsets.UTF_8);
        future.getChannel().writeAndFlush(message);
    }
}
